<?php

/**
 * CRUD module bootstrap
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    modules
 * @subpackage crud
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Bootstrap.php 28 2009-05-10 05:50:27Z monzee $
 */
class Crud_Bootstrap extends Zend_Application_Module_Bootstrap
{
    protected function _initRoutes()
    {
        $front = $this->getApplication()->getResource('frontcontroller');
        $router = $front->getRouter();
        $router->addRoute('crud', new Zend_Controller_Router_Route(
            'crud/:action/:table/*',
            array(
                'module' => 'crud',
                'controller' => 'index',
                'action' => 'index',
                'table' => '',
            ))
        );
    }

    /**
     * I wonder if this is the right place for this.
     *
     * @return Zend_Db_Adapter_Abstract
     */
    public function getAdapter()
    {
        $default = Zend_Db_Table_Abstract::getDefaultAdapter();
        $iniFile = dirname(__FILE__) . '/config.ini';
        $session = new Zend_Session_Namespace('crud');

        if ('default' == $session->adapter || !file_exists($iniFile)) {
            return $default;
        }

        if ('custom' == $session->adapter && !empty($session->adapterParams)) {
            $params = $session->adapterParams;
            $adapter = array_shift($params);
        } else {
            $config = new Zend_Config_Ini($iniFile, 'crud');
            $config = $config->db->toArray();

            if (empty($config) || !empty($config['useDefault'])) {
                return $default;
            }

            $adapter = $config['adapter'];
            $params = $config['params'];
        }

        return Zend_Db::factory($adapter, $params);
    }

}